//
//  DrawerViewController.m
//  囧途
//
//  Created by fly on 16/3/3.
//  Copyright © 2016年 fly. All rights reserved.
//

#import "DrawerViewController.h"
#import "MyOrderViewController.h"
@interface DrawerViewController ()
@property (nonatomic, strong) UIViewController                 *mainViewController;
@property (nonatomic, strong) UIViewController                 *leftViewController;
@property (nonatomic, strong) UIView                           *maskView;
@property (nonatomic, strong) UIScreenEdgePanGestureRecognizer *openGesture;
@property (nonatomic, strong) UIPanGestureRecognizer           *closeGesture;

@end

@implementation DrawerViewController

// controller的初始化方法通常只对属性进行赋值
- (instancetype)initWithMainViewController:(UIViewController *)mainViewController leftViewController:(UIViewController *)leftViewController
{
    self = [super init];
    if (self) {
        self.mainViewController = mainViewController;
        self.leftViewController = leftViewController;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor redColor];
    
    // 关联控制器的父子关系
    // 左抽屉的视图应该在打开左抽屉的时候再加上去
    [self addChildViewController:self.leftViewController];
    // 一开始左抽屉的视图应该在屏幕左边而不是中间
    self.leftViewController.view.frame = CGRectMake(-CGRectGetWidth(self.view.bounds)/2, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
    // 这里没有把左抽屉的视图添加进去是因为左抽屉的视图应该在打开抽屉的时候才显示出来，不然会浪费一定内存
    [self.leftViewController didMoveToParentViewController:self];
    
    [self addChildViewController:self.mainViewController];
    // 默认要一直显示main控制器的视图
    [self.view addSubview:self.mainViewController.view];
    
    [self.mainViewController didMoveToParentViewController:self.mainViewController];

    // 加一个右滑手势
    UIScreenEdgePanGestureRecognizer * openGesture = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(onPanGesture:)];
    // 只能响应屏幕左侧的拖动手势
    openGesture.edges = UIRectEdgeLeft;
    [self.view addGestureRecognizer:openGesture];
    self.openGesture = openGesture;
    
}

// 线性插值

- (CGFloat)interpolateFrom:(CGFloat)from to:(CGFloat)to percent:(CGFloat)percent
{
    return from + (to - from) * percent;
}

- (void)openLeftDrawer
{
    [self handleDrawerWithFlag:YES];
    
}

- (void)closeLeftDrawer
{
    [self handleDrawerWithFlag:NO];
}

- (void)handleDrawerWithFlag:(BOOL)isOpen
{
    CGFloat width = CGRectGetWidth(self.view.frame);
    CGFloat height = CGRectGetHeight(self.view.frame);
    
    // 使用几个变量来控制不同状态下，动画的结束值不同
    CGRect mainToFrame ;
    CGRect leftToFrame ;
    CGFloat maskToAlpha;
    
    if (isOpen) {
       // 打开抽屉，移除右滑打开抽屉的手势
        [self.view removeGestureRecognizer:self.openGesture];
        // 添加遮罩视图
        [self.view addSubview:self.maskView];
        // 打开动画之前，把左抽屉的视图加上去
        [self.view insertSubview:self.leftViewController.view atIndex:0];
        // 打开抽屉，则左抽屉移动到屏幕中间
        leftToFrame = self.view.bounds;
        // 主控制器移动到屏幕右边
        mainToFrame = CGRectMake(width - 50, 0, width, height);
        // 遮罩的透明度变为0.6
        maskToAlpha = 0.6;
        
    } else {
        
        // 关闭抽屉，添加右滑打开抽屉的手势
        [self.view addGestureRecognizer:self.openGesture];
        // 左抽屉移动到屏幕左边
        leftToFrame = CGRectMake(-width/2, 0, width, height);
        // 主控制器移动到屏幕中间
        mainToFrame = self.view.bounds;
        // 遮罩alpha变为0
        maskToAlpha = 0;
        
    }
    // 通过刚才确定的变量来进行动画
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.leftViewController.view.frame = leftToFrame;
        self.mainViewController.view.frame = mainToFrame;
        self.maskView.frame = mainToFrame;
        self.maskView.alpha = maskToAlpha;
    } completion:^(BOOL finished) {
        if (!isOpen) {
            // 如果是关闭抽屉，则移除左视图和mask
            [self.leftViewController.view removeFromSuperview];
            [self.maskView removeFromSuperview];
        }
    }];
}

#pragma mark - callback
- (void)tapOnMask:(UITapGestureRecognizer *)sender
{
    // 点击遮罩视图，关闭抽屉
    [self closeLeftDrawer];
    
}

- (void)onPanGesture:(UIPanGestureRecognizer *)sender
{
    if (sender.state == UIGestureRecognizerStateBegan) {
        // 打开抽屉的一瞬间，添加左抽屉视图
        [self.view insertSubview:self.leftViewController.view atIndex:0];
        // 添加遮罩视图
        [self.view addSubview:self.maskView];
        
    } else if (sender.state == UIGestureRecognizerStateChanged) {
        // 改变几个视图的frame以及alpha
        // 手指一共只能滑300的位移
        CGFloat maxTranslation = 300.f;
        // 手指的位移
        CGPoint translation = [sender translationInView:sender.view];
        if (translation.x < 0) {
            translation.x = 0;
        }
//        NSLog(@"%f",translation.x);
        // 手指当前位移占总位移的百分比
        CGFloat percent = translation.x / maxTranslation;
        // 如果拖出去了，就当拖到最终的状态来处理
        if (percent > 1) {
            percent = 1;
        }
        
        // 遮罩视图的透明度从0变为0.6
        CGFloat fromAlpha = 0;
        CGFloat toAlpha = 0.6;
        // 插值计算手指移到当前位移量的时候透明度应该为多少
        CGFloat alpha = [self interpolateFrom:fromAlpha to:toAlpha percent:percent];
        self.maskView.alpha = alpha;
        
        CGFloat width = CGRectGetWidth(self.mainViewController.view.bounds);
        CGFloat height = CGRectGetHeight(self.view.bounds);
        
        // 主视图控制器的frame的x从0变为距离屏幕右边50的位置
        CGFloat mainFromX = 0;
        CGFloat mainToX = width - 50;
        // 通过线性插值计算当手指移动了translation后，mainView应该移动到哪里
        CGFloat x = [self interpolateFrom:mainFromX to:mainToX percent:percent];
        self.mainViewController.view.frame = CGRectMake(x, 0, width, height);
        // mask跟mainView是一起动的
        self.maskView.frame = self.mainViewController.view.frame;
        
        // 左视图的插值处理
        // 左视图从-屏幕宽的一半移动到0
        CGFloat leftFromX = -width/2;
        CGFloat leftToX = 0;
        // 线性插值计算当前x
        CGFloat leftX = [self interpolateFrom:leftFromX to:leftToX percent:percent];
        self.leftViewController.view.frame = CGRectMake(leftX, 0, width, height);
        
    } else if (sender.state == UIGestureRecognizerStateCancelled || sender.state == UIGestureRecognizerStateEnded) {
        
        // 手指松开后（手势响应结束）
        // 如果这一瞬间速度向右，则打开抽屉，速度向左则关闭抽屉
        CGPoint velocity = [sender velocityInView:sender.view];
        if (velocity.x > 0) {
            [self openLeftDrawer];
        } else {
            [self closeLeftDrawer];
        }
    }
}

#pragma mark - getter
- (UIView *)maskView
{
    if (!_maskView) {
        _maskView = [[UIView alloc] initWithFrame:self.mainViewController.view.bounds];
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnMask:)];
        // 遮罩视图的单击手势，关闭抽屉
        [_maskView addGestureRecognizer:tap];
        
        // 设置阴影效果
        _maskView.layer.shadowColor = [UIColor blackColor].CGColor;
        _maskView.layer.shadowOpacity = 0.8;
        // 设置shadowPath避免离屏渲染
        _maskView.layer.shadowPath = [UIBezierPath bezierPathWithRect:_maskView.bounds].CGPath;
        // 背景色为黑色，改变透明度来达到遮罩的效果
        _maskView.backgroundColor = [UIColor blackColor];
        _maskView.alpha = 0;
    }
    
    return _maskView;
}


@end
